package com.example.chinamobileai.controller;

import cn.hutool.json.JSONUtil;
import com.example.chinamobileai.domain.Rule;
import com.example.chinamobileai.service.IChatHistoryService;
import jakarta.annotation.PostConstruct;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ai")
public class PhonePlanController {

    @Autowired
    private IChatHistoryService chatHistoryService;

    @Autowired
    private ChatClient serviceChatClient;
    @Autowired
    private VectorStore vectorStore;

    // 请求方式和路径不要改动，将来要与前端联调
    @RequestMapping(value = "/service", produces = "text/html;charset=UTF-8")
    public Flux<String> service(@RequestParam(defaultValue = "你好") String prompt, String chatId) {
        // 保存会话历史
        chatHistoryService.saveChatHistory("service", chatId);

        return serviceChatClient
                .prompt(prompt)
                // 设置会话ID
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream() // 流式调用
                .content(); //返回响应内容
    }

    @PostConstruct
    private void writeToVectorStore() throws IOException {
        // 使用 ClassPathResource 读取 resources 目录下的 rule.json
        Resource resource = new ClassPathResource("rule.json");
        String jsonContent = Files.readString(resource.getFile().toPath());
        // 将上面的jsonContent转为Rule对象
        List<Rule> ruleList = JSONUtil.toList(jsonContent, Rule.class);
        List<Document> ruleDocuments = new ArrayList<>();
        for (Rule rule1 : ruleList) {
            String ruleString = JSONUtil.toJsonStr(rule1);
            Document ruleDocument = new Document(ruleString);
            ruleDocuments.add(ruleDocument);
        }
        // 将rule写入向量库
        vectorStore.add(ruleDocuments);
    }

}
